package com.laycoding.layrpc.config.client;

import com.laycoding.layrpc.common.SpringUtils;
import com.laycoding.layrpc.entity.LayRpcProperties;
import com.laycoding.layrpc.handler.client.LayRpcClientRegistry;
import com.laycoding.layrpc.handler.client.RpcCommandLine;
import com.laycoding.layrpc.handler.client.RpcProxyHandler;
import com.laycoding.layrpc.listen.LayRpcListener;
import com.laycoding.layrpc.service.RpcServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(LayRpcProperties.class)
@Slf4j
public class LayRpcAutoConfig {

    @Autowired
    private LayRpcProperties layRpcProperties;


    @Bean(name = "curatorFramework",destroyMethod = "close")
    public  CuratorFramework curatorFramework() {
        CuratorFramework cur = CuratorFrameworkFactory.builder()
                .connectString(layRpcProperties.getZookeeper())
                .connectionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        cur.start();
        return cur;
    }

    @Bean(name = "layRpcListener")
    @ConditionalOnBean(name = "curatorFramework")
    public LayRpcListener layRpcListener(){
        return new LayRpcListener();
    }

    @Bean
    @ConditionalOnBean(name = "curatorFramework")
    public RpcCommandLine rpcCommandLine(){
        return new RpcCommandLine();
    }

    @Bean
    public RpcProxyHandler rpcProxyHandler(){
        return  new RpcProxyHandler();
    }

    @Bean(name = "layRpcClientRegistry")
    public LayRpcClientRegistry layRpcClientRegistry(){
        return  new LayRpcClientRegistry();
    }

    @Bean(name = "rpcService")
    public RpcServiceImpl rpcService(){
        return  new RpcServiceImpl();
    }
    @Bean
    public SpringUtils springUtils(){
        return  new SpringUtils();
  }

}
